/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: MyServletRequestListener
 * Author:   ZX
 * Date:     2020/7/27 18:58
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package org.example.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author ZX
 * @create 2020/7/27
 * @since 1.0.0
 */
//@WebListener
public class MyServletRequestListener implements ServletRequestListener {
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        //用户未登录状态的username值
        String username = "游客";
        //用户名
        //判断当前请求中是否包含用户的登录信息
        if(request.getSession(false) != null
                && request.getSession().getAttribute("user") != null){
            ListenedUser user = (ListenedUser) request.getSession().getAttribute("user");
            username = user.getUsername();
        }
        //用户ip
        String ip = request.getRemoteAddr();
        //用户请求的url地址
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI().toString();

        System.out.println("用户["+username+"]|ip:"+ip+"|uri:"+uri+"访问开始");
    }

    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        //用户未登录状态的username值
        String username = "游客";
        //用户名
        //判断当前请求中是否包含用户的登录信息
        if(request.getSession(false) != null
                && request.getSession().getAttribute("user") != null){
            ListenedUser user = (ListenedUser) request.getSession().getAttribute("user");
            username = user.getUsername();
        }

        //用户ip
        String ip = request.getRemoteAddr();
        //用户请求的url地址
        String url = request.getRequestURL().toString();
        String uri = request.getRequestURI().toString();
        System.out.println("用户["+username+"]|ip:"+ip+"|uri:"+uri+"访问结束");
    }


}